package com.zg.system.auth;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zg.common.core.R;
import com.zg.common.core.User;
import com.zg.common.core.dao.auth.AuthMenu;
import com.zg.common.core.dao.auth.AuthMenuDao;
import com.zg.common.core.dao.auth.AuthUserMenu;
import com.zg.common.core.dao.auth.AuthUserMenuDao;
import com.zg.common.core.util.JsonUtil;
import com.zg.common.web.Req;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class UserMenuController {
    private final AuthUserMenuDao userMenuDao;
    private final AuthMenuDao menuDao;

    @GetMapping("/user/menu/list")
    public R listUserMenu() {
        User user = Req.getCurrUser();
        List<AuthUserMenu> list = userMenuDao.list(new LambdaQueryWrapper<AuthUserMenu>()
                .eq(AuthUserMenu::getUserId, user.getId()));
        ArrayNode an = JsonUtil.an();
        list.stream().forEach(t -> {
            ObjectNode on = JsonUtil.on();
            on.put("relId", String.valueOf(t.getId()));
            on.put("menuId", String.valueOf(t.getMenuId()));
            AuthMenu menu = menuDao.getById(t.getMenuId());
            AuthMenu parentMenu = menuDao.getById(menu.getPid());
            on.put("name", menu.getName());
            on.put("url", "/" + parentMenu.getCode() + "/" + menu.getCode());
            an.add(on);
        });
        return R.success(an);
    }

    @PostMapping("/user/menu/add")
    public R addUserMenu(@RequestBody Long menuId) {
        User user = Req.getCurrUser();
        if (userMenuDao.exists(new LambdaQueryWrapper<AuthUserMenu>()
                .eq(AuthUserMenu::getUserId, user.getId())
                .eq(AuthUserMenu::getMenuId, menuId))) {
            return R.error("您已经保存过这个功能");
        }
        AuthUserMenu obj = new AuthUserMenu();
        obj.setUserId(user.getId());
        obj.setMenuId(menuId);
        userMenuDao.save(obj);
        return R.success();
    }

    @PostMapping("/user/menu/del")
    public R delUserMenu(@RequestBody Long id) {
        userMenuDao.removeById(id);
        return R.success();
    }
}
